<?php

namespace IYUU\sdk\CoolQ\Modules\system\Domain;

use BadRequestException;
use IYUU\sdk\CoolQ\Context;
use IYUU\sdk\CoolQ\Domain\Credit as DomainCredit;
use IYUU\sdk\CoolQ\Event\Message as EventMessage;
use IYUU\sdk\CoolQ\ModulesDomainInterface;
use UserModel;

/**
 * 积分兑换
 * Class CreditsExchange
 * @package IYUU\sdk\CoolQ\Modules\system\Domain
 */
class CreditsExchange implements ModulesDomainInterface
{
    /**
     * 命令分隔符
     */
    const SEP = '/';
    /**
     * @var array
     */
    private $data = [];

    /**
     * 插件状态
     * @return bool
     */
    public function state(): bool
    {
        return true;
    }

    /**
     * 菜单
     * @param string $message 消息内容
     * @return string
     */
    public function menu(string $message): string
    {
        if ($this->keyword() === $message) {
            $reply = '积分兑换操作格式：' . PHP_EOL;
            $reply .= '兑换：兑换{分隔符}目标QQ{分隔符}积分{分隔符}原因' . PHP_EOL;
            $reply .= '查看：查看{分隔符}目标QQ' . PHP_EOL . PHP_EOL;
            //$reply .= '撤销：撤销{分隔符}主键' . PHP_EOL;
            $reply .= '示例：兑换{分隔符}10000{分隔符}500{分隔符}群内抽奖';
            return str_replace('{分隔符}', CreditsExchange::SEP, $reply);
        }

        return '';
    }

    /**
     * 触发的关键字
     * @return string
     */
    public function keyword(): string
    {
        return '积分兑换';
    }

    /**
     * @param Context $context
     * @param EventMessage $msgObj
     * @return string
     * @throws BadRequestException
     */
    public function process(Context $context, EventMessage $msgObj): string
    {
        // 必须工作人员，才能进行的操作
        $msgObj->requireWorker();
        $message = $context->get('message');
        if (empty($message)) {
            return '命令为空';
        }

        // 分隔命令
        if (strpos($message, self::SEP) !== false) {
            $this->data = explode(self::SEP, $message);
        } else {
            return '分隔符不正确';
        }

        // 路由
        switch (true) {
            case (strpos($message, '兑换' . self::SEP) === 0):
                return $this->exchange($context, $msgObj);
            case (strpos($message, '撤销' . self::SEP) === 0):
                return $this->del();
            case (strpos($message, '查看' . self::SEP) === 0):
                return $this->show();
        }

        return '未匹配到命令路由';
    }

    /**
     * 兑换积分
     * @param Context $context
     * @param EventMessage $msgObj
     * @return string
     */
    private function exchange(Context $context, EventMessage $msgObj): string
    {
        /**
         * 验证格式
         */
        if (count($this->data) !== 4) {
            return '格式不正确，数组不等于4';
        }
        $data = array_filter($this->data, function ($v, $k) {
            return $v !== '';
        }, ARRAY_FILTER_USE_BOTH);
        if (count($data) !== count($this->data)) {
            return '格式不正确，数组值不能为空';
        }

        // 1. QQ
        if (!is_numeric($this->data[1])) {
            return 'QQ非数字：' . $this->data[1];
        }
        // 2. 积分
        if (!is_numeric($this->data[2])) {
            return '兑换的积分非数字：' . $this->data[2];
        }
        // 3. 兑换原因
        $content = $this->data[3];
        if (empty($content)) {
            return '兑换原因不能为空';
        }

        $user_id = (int)$this->data[1];
        $credits = (int)$this->data[2];
        if (0 >= $credits) {
            return '兑换的积分值必须大于0';
        }
        $handled_by = $context->get('user_id');
        $rs = DomainCredit::creditsExchange('-', $credits, $user_id, $handled_by, $content);

        return $rs ?? '因未知原因，积分兑换失败，请稍后再试';
    }

    /**
     * 撤销
     * @return string
     */
    private function del(): string
    {
        return '功能开发中...';
    }

    /**
     * 显示
     * @return string
     */
    private function show(): string
    {
        if (count($this->data) !== 2) {
            return '格式不正确，数组不等于2';
        }
        [$cmd, $user_id] = $this->data;

        // QQ
        if (!is_numeric($user_id)) {
            return 'QQ非数字：' . $user_id;
        }

        // 用户信息
        $user = UserModel::where('user_id', $user_id)->findOrEmpty();
        if ($user->isEmpty()) {
            return '不存在用户，QQ:' . $user_id;
        }

        return sprintf('[CQ:face,id=125]QQ：%d' . PHP_EOL . '[CQ:face,id=69]累计积分：%d' . PHP_EOL . '[CQ:face,id=76]已消耗积分：%d', $user_id, $user->credits, $user->credits_exchange);;
    }
}
